package com.co.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ldl.plus
 * @date 2020年06月25日  20:12
 * 全局过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";
    private static final String COOKIE_UID = "uid";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 放行登录等操作
        String path = request.getURI().getPath();
        if (UrlFilter.hasAuthorize(path)) {
            return chain.filter(exchange);
        }

        // 获取令牌 2、参数，1、头信息，3、cookie
        String token = request.getHeaders().getFirst(COOKIE_UID);

        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(COOKIE_UID);
        }
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(COOKIE_UID);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        // 如果还是没有令牌，则拦截请求，如果redis中token不存在，如果redis中token不存在，则拒绝本次访问
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //判断redis中token是否存在，如果不存在，则拒绝本次访问
        String redisToken = stringRedisTemplate.boundValueOps(token).get();
        if (StringUtils.isEmpty(redisToken)) {
            //拒绝访问，请求跳转
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //校验通过，请求头增强，放行
        request.mutate().header(AUTHORIZE_TOKEN, "Bearer " + redisToken);

        return chain.filter(exchange);
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
